<?php


/**
* CakePHP Routines Plugin
* http://cake-routines-plugin.googlecode.com
*
* @package routines
* @subpackage routines.models.behaviors
* @author Ivan Chistyakov <zetruger@gmail.com>
* @version $Id: slugable.php 169 2010-10-22 10:29:02Z zetruger@gmail.com $
* @link $HeadURL: http://cake-routines-plugin.googlecode.com/svn/trunk/models/behaviors/slugable.php $
* @license MIT License (http://opensource.org/licenses/mit-license.php)
*/


class SlugableBehavior extends ModelBehavior {

var $_defaults = array(
	'slugField' => 'slug',
	'slugDisplayField' => 'caption'
);

var $settings = array();

function setup(&$Model, $settings = array()) {
	$this->settings[$Model->alias] = $settings;
}

function _getSettings(&$Model, $settings = array()) {
	$settings = Set::merge($this->settings[$Model->alias], $settings);
	if (isset($settings['noUseModelVars']) && $settings['noUseModelVars']) {
		return Set::merge($this->_defaults, $settings);
	} else {
		return Set::merge($this->_defaults, array_intersect_key(get_object_vars($Model), $this->_defaults), $settings);
	}
}

function beforeSave(&$Model) {
	extract($this->_getSettings($Model), EXTR_SKIP);
	if ($Model->hasField($slugField) && isset($Model->data[$Model->alias][$slugField])) {
		if (empty($Model->data[$Model->alias][$slugField])) {
			if ($Model->hasField($Model->displayField) && isset($Model->data[$Model->alias][$Model->displayField])) {
				$Model->data[$Model->alias][$slugField] = $Model->data[$Model->alias][$Model->displayField];
			} elseif ($Model->hasField($slugDisplayField) && isset($Model->data[$Model->alias][$slugDisplayField])) {
				$Model->data[$Model->alias][$slugField] = $Model->data[$Model->alias][$slugDisplayField];
			}
		}
		$Model->data[$Model->alias][$slugField] = Inflector::slug($Model->data[$Model->alias][$slugField]);
	}
	return TRUE;
}

}


?>